package com.songlanyun.common.utils.custom;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 匹配工具辅助类
 */
public class PatternUtils
{
    /**
     * 判断金额，最多保留两位小数
     * @param str 金额
     * @return Boolean
     */
    public static boolean price(String str)
    {
        Pattern pattern = Pattern.compile("^\\d+(\\.\\d{1,2})?$");
        Matcher matcher = pattern.matcher(str);
        return matcher.find();
    }

    /**
     * 判断折扣，最多保留一位小数
     * @param str
     * @return
     */
    public static boolean discount(String str)
    {
        Pattern pattern = Pattern.compile("^\\d+(\\.\\d)?$");
        Matcher matcher = pattern.matcher(str);
        return matcher.find();
    }

    /**
     * 判断字符串是否为数字
     * @param str 待匹配字符串
     * @return Boolean
     */
    public static boolean numeric(String str)
    {
        Pattern pattern = Pattern.compile("^\\d*$");
        Matcher matcher = pattern.matcher(str);
        return matcher.find();
    }

    /**
     * 判断字符串是否为手机号
     * @param str 待匹配字符串
     * @return Boolean
     */
    public static boolean phone(String str)
    {
        Pattern pattern = Pattern.compile("^1\\d{10}$");
        Matcher matcher = pattern.matcher(str);
        return matcher.find();
    }


    /**
     * 判断字符串是否仅含数字和字母
     * @param str
     * @return
     */
    public static boolean isLetterDigit(String str) {
        String regex = "^[a-z0-9A-Z]+$";
        return str.matches(regex);
    }


    /**
     * 手机号脱敏处理
     * @param phone 手机号
     * @return 返回示例 138****4568
     */
    public static String insensitiveOfPhone(String phone)
    {
        Pattern pattern = Pattern.compile("^(\\d{3})\\d{4}(\\d{4})$");
        return pattern.matcher(phone).replaceAll("$1****$2");
    }

    /**
     * 去掉金额末尾的0
     * @param price
     * @return
     */
    public static String dislodgeZeroOfPrice(String price)
    {
        if(price.indexOf(".") > 0)
        {
            //去掉后面无用的零
            price = price.replaceAll("0+?$", "");
            //如最后一位是.则去掉
            price = price.replaceAll("[.]$", "");
        }
        return price;
    }
}
